﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;

#endregion


namespace ESF.General.Network
{
	public static class NetworkHelper
	{
		public static void Connect (this Socket pSocket, EndPoint pEndpoint, TimeSpan pTimeout)
		{
			IAsyncResult result;
			
			bool success;

			
			result = pSocket.BeginConnect (pEndpoint, null, null);

			success = result.AsyncWaitHandle.WaitOne (pTimeout, true);

			if (success)
			{
				pSocket.EndConnect (result);
			}
			else
			{
				pSocket.Close();
				throw new SocketException (10060);
			}
		}


		public static bool VerifyIPorFQDN (string pIPorHostName)
		{
			IPAddress tmpIP;


			try
			{
				if (IPAddress.TryParse (pIPorHostName, out tmpIP))
				{
					return true;
				}

				Dns.GetHostEntry (pIPorHostName);

				return true;
			}
			catch (Exception)
			{
				return false;
			}
		}


		public static bool VerifyIPorFQDN(string pIPorHostName, out IPAddress pFirstIPAddresses)
		{
			List<IPAddress> addresses;

			bool result;


			result = VerifyIPorFQDN (pIPorHostName, out addresses);

			pFirstIPAddresses = addresses.First ();

			return result;
		}


		public static bool VerifyIPorFQDN(string pIPorHostName, out List<IPAddress> pIPAddresses)
		{
			IPAddress tmpIP;


			try
			{
				if (IPAddress.TryParse(pIPorHostName, out tmpIP))
				{
					pIPAddresses = new List<IPAddress> () { tmpIP };

					return true;
				}

				pIPAddresses = new List<IPAddress> (Dns.GetHostEntry(pIPorHostName).AddressList);

				return true;
			}
			catch (Exception)
			{
				pIPAddresses = null;

				return false;
			}
		}
	}
}
